package com.xywy.tangandroid.activity;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import org.json.JSONException;
import org.json.JSONObject;

import android.content.Context;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.android.volley.VolleyError;
import com.google.gson.reflect.TypeToken;
import com.xywy.tangandroid.R;
import com.xywy.tangandroid.adapter.SystemMessageAdapter;
import com.xywy.tangandroid.base.BaseActivity;
import com.xywy.tangandroid.bean.SystemMessageData;
import com.xywy.tangandroid.bean.User;
import com.xywy.tangandroid.greendao.DaoMaster;
import com.xywy.tangandroid.greendao.DaoMaster.DevOpenHelper;
import com.xywy.tangandroid.greendao.DaoSession;
import com.xywy.tangandroid.greendao.SystemMessageDataDao;
import com.xywy.tangandroid.util.Constant;
import com.xywy.tangandroid.util.JsonUtil;
import com.xywy.tangandroid.util.LogUtil;
import com.xywy.tangandroid.util.UIUtil;
import com.xywy.tangandroid.vollery.OnVolleyResponseListener;
import com.xywy.tangandroid.vollery.PostRequest;

/**
 * 系统消息
 * 
 * @deprecated 当前页面处理逻辑： 1，从本地获取之前的数据，并且展示 2，从服务器获取数据 添加到之前本地数据中，并且展示；
 *             展示之后存储到本地设置成已读
 * 
 */
public class SystemMessageAct extends BaseActivity {

	private static final String TAG = "SystemMessageAct";
	private SystemMessageAdapter adatper;
	private SharedPreferences sp;
	private Editor editor;

	private RelativeLayout left_img;// 标题返回按钮
	private ListView lv_message; // 系统消息展示；
	private TextView middle_title; // 标题

	private List<SystemMessageData> systemMessage = new ArrayList<SystemMessageData>();
	private List<SystemMessageData> temp = new ArrayList<SystemMessageData>();

	/* 初始化GreenDao */
	private SQLiteDatabase db;
	private DaoMaster daoMaster;
	private DaoSession daoSession;
	private SystemMessageDataDao msgDao;

	@Override
	protected void initView(Bundle savedInstanceState) {
		setContentView(R.layout.act_system_message);
		lv_message = (ListView) findViewById(R.id.lv_message);
		middle_title = (TextView) findViewById(R.id.middle_title);
		middle_title
				.setText(getResources().getString(R.string._system_message));
		left_img = (RelativeLayout) findViewById(R.id.left_img);

		initDao();
	}

	/**
	 * 初始化数据库
	 */
	private void initDao() {
		DevOpenHelper helper = new DaoMaster.DevOpenHelper(this, "notes-db",
				null);
		db = helper.getWritableDatabase();
		daoMaster = new DaoMaster(db);
		daoSession = daoMaster.newSession();
		msgDao = daoSession.getSystemMessageDataDao();
	}

	@Override
	protected void initListener() {
		left_img.setOnClickListener(this);
	}

	@Override
	public void onClick(View v) {
		super.onClick(v);
		switch (v.getId()) {
		case R.id.left_img:
			this.finish();
			break;

		default:
			break;
		}
	}

	@Override
	protected void initData() {
		getLocalData();
		getServerData();
	}

	/**
	 * 获取本地数据
	 */
	private void getLocalData() {
		systemMessage = msgDao.loadAll();
		adatper = new SystemMessageAdapter(this, systemMessage);
		if (systemMessage.size() > 0) {
			lv_message.setAdapter(adatper);
		} else {
			// TODO: 展示没有数据的界面
		}

	}

	/**
	 * 从服务器获取当前设备数据
	 */
	private void getServerData() {
		// http://api.yun.xywy.com/index.php/glu_app/ad/msg_box/
		PostRequest<String> postRequest = new PostRequest<String>(
				Constant.MESSAGE_URL + "/msg_box/", String.class,
				new OnVolleyResponseListener<String>() {

					@Override
					public void onError(VolleyError volleyError) {
						UIUtil.DissDialog(context, waittingDialog);
						UIUtil.showToast(context, context.getResources()
								.getString(R.string.network_slow));
					}

					@Override
					public void onSuccess(String response) {
						UIUtil.DissDialog(context, waittingDialog);

						try {
							ParserData(response);
						} catch (JSONException e) {
							e.printStackTrace();
						}
					}

				});

		sp = getSharedPreferences("config", Context.MODE_PRIVATE);
		long lastTime = sp.getLong("system_message_last_save", 1);
		HashMap<String, String> params = new HashMap<String, String>();
		params.put("xywy_userid", User.getIUserInstance(context).getUserid());// userID
		params.put("datatime", lastTime + "");// 最后一条时间
		params.put("fromurl", "app_tang");// 最后一条时间
		params.put("type", 1 + "");// password
		postRequest.setParams(params);
		postRequest.setIsParseJson(false);
		executeRequest(postRequest);

	}

	/**
	 * 解析当前从服务器上获取的数据
	 * 
	 * @param response
	 *            获取的String
	 * @throws JSONException
	 *             json解析异常
	 */
	private void ParserData(String response) throws JSONException {
		JSONObject jsonObject = new JSONObject(response);
		int state = jsonObject.getInt("state");
		if (state == 200) { // 请求成功
			// 更新最后一次拉取的时间
			editor = sp.edit();
			editor.putLong("system_message_last_save",
					System.currentTimeMillis() / 1000); // 每次保存就是使用与ios相同的时间
			String data = jsonObject.getString("data");
			
			
			temp.addAll((List<SystemMessageData>) JsonUtil.parseJsonToList(
					data, new TypeToken<List<SystemMessageData>>() {
					}.getType()));

			/*
			 * 此处做两个处理 <br> 1，将temp的数值添加到systemMessage中，此时的temp 所有数据都是1的，表示未读
			 * <br> 2，将temp的数据添加到本地，此时的temp 所有数据都是0的，表示已读
			 */

			temp = dealTemp(temp);
			if (temp != null && temp.size() > 0) {
				adatper.setAddList(temp);
				lv_message.setAdapter(adatper);
			} else {
				LogUtil.d(TAG, "没有新的消息");
			}
			insertLocal(temp);

		}
	}

	/**
	 * 将数据存储到本地
	 * 
	 * @param temp2
	 */
	private void insertLocal(List<SystemMessageData> temp2) {
		for (SystemMessageData data : temp2) {
			data.setState(0);
			msgDao.insert(data);
		}
	}

	/**
	 * 循环为每一个data设置状态
	 * 
	 * @param temp2
	 * @return
	 */
	private List<SystemMessageData> dealTemp(List<SystemMessageData> temp2) {
		for (SystemMessageData data : temp2) {
			data.setState(1);
		}
		return temp2;
	}

	/**
	 * 处理非主线程数据
	 */
	Handler handler = new Handler() {
	};

}
